// schema扩展相关文档请参阅：https://uniapp.dcloud.net.cn/uniCloud/jql-schema-ext.html
module.exports = {
	trigger: {
		beforeCreate: async function({
			addDataList
		} = {}) {
			// 在写入数据库前按当天日期和当天店铺新增商品序号生成本店铺唯一且按序排列的商品货号
			//在此处生成，也避免了多人同时为某一店铺添加商品时出现冲突
			const dbJQL = uniCloud.databaseForJQL()
			let todayDate = new Date().setHours(8, 0, 0, 0); //按中国时间的当天时间值
			let todayCount, last;
			let lastNum = 0;
			for (let i = 0; i < addDataList.length; i++) {
				let addDataItem = addDataList[i]

				todayCount = await dbJQL.collection('opendb-mall-goods').where(
					`shop_id=='${addDataItem.shop_id}' && add_date > ${todayDate}`).count()
				if (todayCount.total > 0) {
					last = await dbJQL.collection('opendb-mall-goods').where(
						`shop_id=='${addDataItem.shop_id}' && add_date > ${todayDate}`).field(
						'goods_sn').limit(
						1).orderBy('add_date desc').get()
					lastNum = last.data[0].goods_sn.split('-').reverse()[0] * 1
				}
				// count=todayCount.total

			}
			for (let i = 0; i < addDataList.length; i++) {
				let addDataItem = addDataList[i]
				addDataItem.goods_sn = addDataItem.goods_sn.replace('- ?', '')
				addDataItem.goods_sn = addDataItem.goods_sn + "-" + (lastNum + i + 1)
			}
		}
	}
}